package com.tsin.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tsin.usercenter.exception.BusinessException;
import com.tsin.usercenter.common.ErrorCode;
import com.tsin.usercenter.mapper.UserMapper;
import com.tsin.usercenter.model.User;
import com.tsin.usercenter.service.UserService;
import com.tsin.usercenter.utils.AlgorithmUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.apache.commons.math3.util.Pair;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.tsin.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.tsin.usercenter.constant.UserConstant.USER_LOGIN_KEY;

/**
 * @author 佳宏
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-08-10 20:45:52
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * SALT 盐值
     */
    private static final String SALT = "jiahong";


    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 验证密码
     * @return id 用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "参数为空");

        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度过短（4）");
        }
        if (userPassword.length() < 6 || checkPassword.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度过短（6）");
        }
        //不包含特殊符号
        String vaildPattern = "[`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vaildPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "包含有不合法的特殊字符");
        }
        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "有重复账户存在");
        }

        //2.加密

        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setPassword(newPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();

    }

    /**
     * 登录逻辑
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return User 用户
     */
    @Override
    public Long userDoLogin(String userAccount, String userPassword, HttpServletRequest httpServletRequest) {
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new RuntimeException("账户密码为空");
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 6) {
            return null;
        }

        //不包含特殊符号
        String vaildPattern = "^[^!@#$%^&*()-=+{}|\\[];:\\'\",.<>?/]+$";
        Matcher matcher = Pattern.compile(vaildPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        try {
            //查询
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", userAccount);
            queryWrapper.eq("password", newPassword);
            User user = userMapper.selectOne(queryWrapper);
            long count = this.count(queryWrapper);
            if (user == null) {
                log.info("user login failed,userAccount cannot match userPassword");
                return null;

            }

            //3.脱敏
            User safeUser = getSafetyUser(user);
            //4.记录登录状态
            httpServletRequest.getSession().setAttribute(USER_LOGIN_KEY, safeUser);
            Long id = safeUser.getId();
            return id;
        } catch (Exception ex) {
            log.error("111", ex);
        }
        return null;

    }

    /**
     * 脱敏方法
     *
     * @param user 脱敏前user
     * @return 脱敏后user
     */
    public User getSafetyUser(User user) {
        if (user == null) {
            return null;
        }
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setNickName(user.getNickName());
        safeUser.setUserAccount(user.getUserAccount());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setGender(user.getGender());
        safeUser.setPhone(user.getPhone());
        safeUser.setEmail(user.getEmail());
        safeUser.setCreateTime(user.getCreateTime());
        safeUser.setUpdateTime(user.getUpdateTime());
        safeUser.setUserRole(user.getUserRole());
        safeUser.setUserStatus(user.getUserStatus());
        safeUser.setTags(user.getTags());
        return safeUser;
    }


    /**
     * 用户注销
     *
     * @param httpServletRequest
     */
    @Override
    public int userLoginOut(HttpServletRequest httpServletRequest) {
        //移除用户登录态
        httpServletRequest.getSession().removeAttribute(USER_LOGIN_KEY);
        return 1;

    }

    @Override
    public List<User> searchUserByTagsBySql(List<String> tagsNameList) {
        //数据库查询方法
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagName : tagsNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> safetyUserList = new ArrayList<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        for (User user : userList) {
            User safetyUser = getSafetyUser(user);
            safetyUserList.add(safetyUser);
        }
        return userList;
    }

    @Override
    public List<User> searchUserByTags(int pageSize,int pageNum,List<String> tagsNameList) {
        //内存查询方式
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> safetyUserList = new ArrayList<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagsNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());

    }

    @Override
    public Integer updateUser(User user, User loginUser) {
        Long id = user.getId();
        //校验权限(仅管理员和自己可以更新)
        //如果是管理员，可以更新别人的
        if (isAdmin(loginUser)) {
            User oldUser = userMapper.selectById(id);
            return userMapper.updateById(user);
        }
        //如果不是管理员，只允许更新自己的
        if (!isAdmin(loginUser) && !Objects.equals(id, loginUser.getId())) {
            {
                throw new BusinessException(ErrorCode.NOT_LOGIN);
            }
        }
        return userMapper.updateById(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest httpServletRequest) {
        if (httpServletRequest == null) {
            return null;
        }
        Object attribute = httpServletRequest.getSession().getAttribute(USER_LOGIN_KEY);
        if (attribute == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) attribute;
    }

    @Override
    public boolean isAdmin(HttpServletRequest httpServletRequest) {
        // 仅管理员可查询
        Object userObject = httpServletRequest.getSession().getAttribute(USER_LOGIN_KEY);
        User currentUser = (User) userObject;
        return currentUser != null && currentUser.getUserRole() == ADMIN_ROLE;
    }

    @Override
    public boolean isAdmin(User loginUser) {
        // 仅管理员可查询
        return loginUser != null && loginUser.getUserRole() == ADMIN_ROLE;
    }



    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }

}






